package controllers;

import java.util.List;

import models.Post;
import play.cache.Cache;
import play.data.validation.Required;
import play.libs.Codec;
import play.libs.Images;
import play.mvc.Before;

public class Home extends Application {
    //首页
    public static void index() {
        Post frontPost = Post.find("order by postedAt desc").first();
        List<Post> olderPosts = Post.find("order by postedAt desc").from(1).fetch(10);
        render(frontPost, olderPosts);
    }
    
    public static void show(Long id) {
        Post post = Post.findById(id);
        String randomID = Codec.UUID();
        render(post, randomID);
    }
    public static void captcha(String id) {
        Images.Captcha captcha = Images.captcha();
        String code = captcha.getText("#E4EAFD");
        Cache.set(id, code, "10mn");
        renderBinary(captcha);
    }
    public static void postComment(Long postId,
                                   @Required(message = "请输入姓名") String author,
                                   @Required(message = "请输入评论内容") String content,
                                   @Required(message = "请输入验证码") String code,
                                   String randomID) {
        Post post = Post.findById(postId);
        validation.equals(code, Cache.get(randomID)).message("Invalid code. Please type it again");
        if (validation.hasErrors()) {
            render("Home/show.html", post, randomID);
        }
        post.addComment(author, content);
        flash.success("评论成功", author);
        Cache.delete(randomID);
        show(postId);
    }
    
    public static void listTagged(String tag) {
        List<Post> posts = Post.findTaggedWith(tag);
        render(tag, posts);
    }
}
